// 接口服务器基地址
import { useMemberStore } from '@/store/member'
const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
// 注册请求拦截器
uni.addInterceptor('request', {
  invoke(arg) {
    // 判断请求路径中是否携带基地址
    if (!(arg.url as string).startsWith('https')) arg.url = baseURL + arg.url
    // 获取 token
    const memberStore = useMemberStore()
    const token = memberStore.profile.token
    // 判断是否有 token
    if (token) {
      // token：存在将 token 添加到请求头中
      arg.header = { Authorization: `Bearer ${token}` }
    }
  },
})

type TRes = {
  code: string
  msg: string
  result: any
}

export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<T>((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) return resolve((res.data as TRes).result)
        uni.showToast({ title: (res.data as any).msg, icon: 'none' })
        // 失败后的逻辑
        reject(res)
      },
      fail: (err) => {
        console.log('请求失败的回调: fail')
        reject(err)
      },
    })
  })
}

// uploadFile 添加拦截器
uni.addInterceptor('uploadFile', {
  invoke(arg) {
    // 判断请求的路径中是否携带基地址；将请求的路径拼接上基地址
    if (!(arg.url as string).startsWith('https:')) arg.url = baseURL + arg.url
    // 获取 token
    const memberStore = useMemberStore()
    const token = memberStore.profile.token
    // 判断是否存在 token：存在将 token 添加到请求头中
    if (token) arg.header = { Authorization: `Bearer ${token}` }
  }
})